<template>
    <div
        style="display: flex; flex-direction: column;align-items: center;line-height: 40px;font-size: 20px;width: 210mm;margin: 0 auto;background-color: #fff;padding: 20px;">
        <div class="filter-container">
            <el-button class="filter-item" type="primary" icon="el-icon-back" @click="goBack">返回</el-button>
            <span>
                <el-button type="success" icon="el-icon-check" v-if="!isView" class="filter-item"
                    @click="saveData">保存</el-button>
                <el-button type="primary" icon="el-icon-menu" class="filter-item" @click="goToList">列表</el-button>
                <!-- <el-button class="filter-item" type="primary" @click="printToPDF">打印PDF</el-button> -->

                <el-button type="info" icon="el-icon-printer" @click="printForm">打印</el-button>
            </span>
        </div>
        <div class="agreement-container" style="height: auto;text-align: left;">
            <h2 style="text-align: center;">协 议 书</h2>
            <hr style="border-color: black;">
            <div class="section">
                <h3>甲方（用人单位）</h3>
                <div class="form-item">
                    <label>企业名称：</label>
                    <input v-model="agreementData.companyName" :disabled="isView">
                </div>
                <div class="form-item">
                    <label>地址：</label>
                    <input style="width: 60%;" v-model="agreementData.companyAddress" value="深圳宝安区沙井镇兴业西路裕达富工业园"
                        readonly>
                </div>
            </div>
            <div class="section">
                <h3>乙方（员工）</h3>
                <div class="form-item">
                    <label>姓名：</label>
                    <input v-model="agreementData.employeeName" :disabled="isView">
                    <label>&emsp;&emsp;&emsp;部门/职务：</label>
                    <input v-model="agreementData.departmentPosition" :disabled="isView">
                </div>
                <div class="form-item">
                    <label>性别：</label>
                    <input v-model="agreementData.employeeGender" :disabled="isView">
                    <label>&emsp;&emsp;&emsp;年龄：</label>
                    <input v-model="agreementData.employeeAge" :disabled="isView">
                </div>
                <div class="form-item">
                    <label>民族：</label>
                    <input v-model="agreementData.nationality" :disabled="isView">
                    <label>&emsp;&emsp;&emsp;户口所在地：</label>
                    <input v-model="agreementData.hukouLocation" :disabled="isView">
                </div>
                <div class="form-item">
                    <label>身份证号码：</label>
                    <input v-model="agreementData.idNumber" :disabled="isView">
                    <label>联系电话：</label>
                    <input v-model="agreementData.contactPhone" :disabled="isView">
                </div>
            </div>
            <div class="section">
                <p>甲乙双方本着平等自愿、协商一致的原则，达成如下协议：</p>
                <div class="clause">
                    <p style="text-indent: 2em;">一、协议人自述：</p>
                    <p style="text-indent: 2.5em;">本人洁身自爱，自觉维护公司利益，决不做对公司有害之事，在职期间忠于职守，为司所用，如有违反，任公司处置必要时需追究本人的刑事责任。<span style="color: blue;">（自述人：
                            <input style="border-bottom: 1px solid blue; width: 15%;" v-model="agreementData.selfDeclarer"
                                :disabled="isView"> ）</span></p>
                </div>
                <div class="clause">
                    <p style="text-indent: 2em;">二、协议人在受聘期间忠于职守，维护公司的技术和商业秘密，不得泄露公司技术资料及严格遵守公司财</p>
                    <p>产安全制度。</p>
                </div>
                <div class="clause">
                    <p style="text-indent: 2em;">三、本人 <input style="border-bottom: 1px solid;width: 18%;" v-model="agreementData.volunteerName"
                            :disabled="isView">
                        自愿与公司签订协议书，并以公司立场愿意为公司储备</p>
                    <p>金额2000元作为公司资产风险金 <span
                            style="color: blue;">（原则上在职的资产保管岗位均需提供有效担保人担保并立出担保书，无担保人者将自愿储备2000元作为公司资产风险金，有担保者将自愿为公司储备1000元作为公司资产风险金，本人无任何异议），四个月内分期从本人工资中扣除，</span>到离职时持公司开出的证明单据予以退回。
                    </p>
                </div>
                <div class="clause">
                    <p style="text-indent: 2em; ">四、协议人如违反上述内容从事了有损公司利益等行为（如：利用职权之便，索取个人利益及损害公司财</p>
                    <p>产、破坏公司形象及名誉者），需要承担相应的经济民事责任时，协议人愿意承担责任，直到公司的损失得到价值补偿为止，并不受公司给予的任何延期、豁免的影响，同时在此预先声明放弃一切抗辩权。
                    </p>
                </div>
            </div>
            <div class="sign-section">
                <div class="form-item">
                    <label>甲方：</label>
                    <input style="border-bottom: 1px solid;" v-model="agreementData.companySignature"
                        :disabled="isView"> 公司
                    <label>&emsp;&emsp;&emsp;乙方：</label>
                    <input v-model="agreementData.employeeSignature" :disabled="isView">
                </div>
                <div class="form-item">
                    <label>日期：</label>
                    <input v-model="agreementData.companyDate" type="date" :disabled="isView">
                    <label>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;日期：</label>
                    <input v-model="agreementData.employeeDate" type="date" :disabled="isView">
                </div>
            </div>
            <div class="note">（附协议人身份证复印件一份）</div>
            <div class="footer">
                <p style="display: flex;justify-content: space-between;"><span>表单编号及版本：AM-JY-265
                        B/0</span>
                    <span>保存期限：长期</span>
                </p>
            </div>
        </div>
    </div>
</template>

<script>
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
import { saveAgreement, getAgreementById } from '@/api/agreement';

export default {
    data() {
        return {
            isView: false,
            agreementData: {
                companyName: '',
                companyAddress: '深圳宝安区沙井镇兴业西路裕达富工业园',
                employeeName: '',
                departmentPosition: '',
                employeeGender: '',
                employeeAge: null,
                nationality: '',
                hukouLocation: '',
                idNumber: '',
                contactPhone: '',
                selfDeclarer: '',
                volunteerName: '',
                companySignature: '',
                companyDate: '',
                employeeSignature: '',
                employeeDate: ''
            }
        };
    },
    created() {
        const { id, type } = this.$route.query;
        if (id) {
            this.fetchData(id);
        }
        this.isView = type === 'view';
    },
    methods: {
        printForm() {
            window.print()
        },

        validatePhone(phone) {
            const phoneRegex = /^1[3-9]\d{9}$/; // 简单的手机号验证正则表达式
            return phoneRegex.test(phone);
        },
        fetchData(id) {
            getAgreementById(id).then(response => {
                const data = response.data;
                if (data.companyDate) {
                    data.companyDate = this.formatDate(data.companyDate);
                }
                if (data.employeeDate) {
                    data.employeeDate = this.formatDate(data.employeeDate);
                }
                this.agreementData = data;
            }).catch(error => {
                this.$message({
                    type: 'error',
                    message: '获取数据失败：' + error.message
                });
            });
        },
        formatDate(date) {
            if (!date) return '';
            const d = new Date(date);
            return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
        },
        saveData() {
            if (!this.validateForm()) {
                return;
            }
            if (!this.validatePhone(this.agreementData.contactPhone)) {
                this.$message({
                    type: 'warning',
                    message: '请输入有效的手机号'
                });
                return;
            }
            saveAgreement([this.agreementData])
                .then(() => {
                    this.$message({
                        type: 'success',
                        message: '保存成功！'
                    });
                    this.$router.push('/main/renshi/renshizhidu/xieyishu/xieyishuList');
                })
                .catch(error => {
                    this.$message({
                        type: 'error',
                        message: '保存失败：' + error.message
                    });
                });
        },
        validateForm() {
            if (!this.agreementData.employeeName) {
                this.$message({
                    type: 'warning',
                    message: '请输入员工姓名'
                });
                return false;
            }
            if (!this.agreementData.departmentPosition) {
                this.$message({
                    type: 'warning',
                    message: '请输入部门/职务'
                });
                return false;
            }
            if (!this.agreementData.employeeSignature) {
                this.$message({
                    type: 'warning',
                    message: '请输入员工签名'
                });
                return false;
            }
            return true;
        },
        printToPDF() {
            const doc = new jsPDF('p', 'pt', 'a4');
            const element = document.querySelector('.agreement-container');
            html2canvas(element).then((canvas) => {
                const imgData = canvas.toDataURL('image/png');
                const imgWidth = 522;
                const pageHeight = 841.89;
                const imgHeight = (canvas.height * imgWidth) / canvas.width;
                let positionY = 0;
                if (imgHeight >= pageHeight) {
                    let leftHeight = imgHeight;
                    while (leftHeight >= pageHeight) {
                        doc.addImage(imgData, 'PNG', 40, positionY, imgWidth, pageHeight);
                        positionY += pageHeight;
                        doc.addPage();
                        leftHeight -= pageHeight;
                    }
                    doc.addImage(imgData, 'PNG', 40, positionY, imgWidth, leftHeight);
                } else {
                    doc.addImage(imgData, 'PNG', 40, positionY, imgWidth, imgHeight);
                }
                doc.save('协议书.pdf');
            });
        },
        goBack() {
            this.$router.push('/main/renshi/renshizhidu');
        },
        goToList() {
            this.$router.push('/main/renshi/renshizhidu/xieyishu/xieyishuList');
        }
    }
};
</script>

<style scoped>
.filter-container {
    width: 100%;
    display: flex;
    justify-content: space-between;
    margin: 10px;
}

.agreement-container {
    width: 100%;
}

.section {
    /* margin-bottom: 20px; */
}

.form-item {
    margin-bottom: 5px;
}

.clause {
    /* margin-bottom: 15px; */
}

.footer {
    text-align: center;
    margin-top: 20px;
}

input {
    border: 0px;
    width: 34%;
    font-size: 20px;
    background-color: rgba(228, 227, 227, 0.4);
}
@media print{
    .filter-container{
        display: none;
    }
}
</style>